<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template #menu="{ row }">
        <el-button type="text" size="small" icon="el-icon-view" plain @click="orderView(row)">查看
        </el-button>
      </template>
    </avue-crud>

    <!-- 订单详情弹窗 -->
    <el-dialog title="订单详情" :visible.sync="detailVisible" width="700px" append-to-body>
      <el-descriptions border :column="2" v-if="orderDetail">
        <el-descriptions-item label="订单号">{{ orderDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="场地名称">{{ orderDetail.courtName }}</el-descriptions-item>
        <el-descriptions-item label="套餐名称">{{ orderDetail.courtPackageName }}</el-descriptions-item>
        <el-descriptions-item label="预定日期">{{ orderDetail.courtDate }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ orderDetail.contactName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ orderDetail.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="联系人数">{{ orderDetail.contactNum }}</el-descriptions-item>
        <el-descriptions-item label="金额">{{ orderDetail.price }}元</el-descriptions-item>
        <el-descriptions-item label="支付状态">{{ getPayStatus(orderDetail.status) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ orderDetail.createTime }}</el-descriptions-item>
      </el-descriptions>

      <div class="order-contact-list"
        v-if="orderDetail && orderDetail.orderContactList && orderDetail.orderContactList.length > 0">
        <el-divider content-position="left">场次列表</el-divider>
        <el-table :data="orderDetail.orderContactList" border style="width: 100%">
          <el-table-column label="日期" width="140">
            <template slot-scope="scope">
              {{ formatDate(scope.row.courtDate) }}
            </template>
          </el-table-column>
          <el-table-column label="场次时间">
            <template slot-scope="scope">
              {{ formatTime(scope.row.startTime) }} ~ {{ formatTime(scope.row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="price" label="金额">
            <template slot-scope="scope">
              {{ scope.row.price }}元
            </template>
          </el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from "@/api/lanqiu/courtOrder";
import option from "@/const/lanqiu/courtOrder";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: [],
      detailVisible: false,
      orderDetail: null
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.courtOrder_add, false),
        viewBtn: this.vaildData(this.permission.courtOrder_view, false),
        delBtn: this.vaildData(this.permission.courtOrder_delete, false),
        editBtn: this.vaildData(this.permission.courtOrder_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    orderView(row) {
      this.detailVisible = true;
      this.loading = true;
      getDetail(row.id).then(res => {
        if (res.data && res.data.data) {
          this.orderDetail = res.data.data;
        } else {
          this.$message.error('获取订单详情失败');
        }
        this.loading = false;
      }).catch(() => {
        this.$message.error('获取订单详情失败');
        this.loading = false;
      });
    },
    getPayStatus(status) {
      const statusMap = {
        '0': '未支付',
        '1': '已支付',
        '2': '已取消'
      };
      return statusMap[status] || status;
    },
    formatDate(dateStr) {
      if (!dateStr) return '';
      // 如果是完整的日期时间格式，提取日期部分
      if (dateStr.includes(' ')) {
        return dateStr.split(' ')[0];
      }
      return dateStr;
    },
    formatTime(timeStr) {
      if (!timeStr) return '';
      // 如果是完整的日期时间格式，提取时间部分
      if (timeStr.includes(' ')) {
        return timeStr.split(' ')[1];
      }
      return timeStr;
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
.order-contact-list {
  margin-top: 20px;
}
</style>
